#include "paywindow.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include "alipaydialog.h"
#include "firstwindow.h"
#include "flightscheckwindow.h"
#include "interfacemanager.h"
#include "models.h"
#include "paydialog.h"
#include "ui_paywindow.h"
#include "userordertestwindow.h"
#include "wechatpaydialog.h"

PayWindow::PayWindow(QWidget *parent, int x, int y)
    : QMainWindow(parent)
    , ui(new Ui::PayWindow)
    , e_userId(x)
    , orderId(y)
{
    ui->setupUi(this);
    manager = new QNetworkAccessManager(this); // 初始化 QNetworkAccessManager
    on_PayWindowInitialized();
}

PayWindow::~PayWindow()
{
    delete ui;
}

void PayWindow::on_PayWindowInitialized()
{
    // e_userId = x; // 假设已得到user的id
    // orderId = y; // 假设已得到 orderId

    // 创建一个 JSON 对象，封装请求体
    QJsonObject json;
    json["user_id"] = e_userId;

    qDebug() << "Preparing request data:" << json;

    // 将 JSON 对象转换为 JSON 文档
    QJsonDocument doc(json);
    QByteArray requestData = doc.toJson();

    QNetworkRequest request(QUrl("http://127.0.0.1:8080/api/orders/search"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = manager->post(request, requestData);
    connect(reply, &QNetworkReply::finished, this, &PayWindow::onGetOrderInfoFinished);
}

void PayWindow::onGetOrderInfoFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (reply->error() != QNetworkReply::NoError) {
        QMessageBox::critical(this, "Error", "Failed to fetch order information.");
        return;
    }

    QByteArray responseData = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(responseData);
    QJsonObject jsonResponse = doc.object();
    qDebug() << "Response: " << jsonResponse;

    if (jsonResponse["code"].toInt() == 200) {
        QJsonArray orders = jsonResponse["data"].toArray();
        bool found = false; // 用于标记是否找到订单

        for (const QJsonValue &value : orders) {
            QJsonObject order = value.toObject();
            int currentOrderId = order["id"].toInt();
            qDebug() << "Checking order ID: " << currentOrderId;

            if (currentOrderId == orderId) {
                found = true; // 找到订单
                double price = order["price"].toDouble();
                qDebug() << "Found order with order_id:" << orderId << " and price:" << price;

                ui->label_Amount->setText("订单金额  " + QString("%1").arg(price) + " CNY");

                QJsonObject flightInfo = order["flight_info"].toObject();
                QString departure = flightInfo["departure"].toString();
                QString destination = flightInfo["destination"].toString();
                QString departureAirport = flightInfo["departureAirport"].toString();
                QString destinationAirport = flightInfo["destinationAirport"].toString();
                QString departureTime = flightInfo["departure_time"].toString();
                QString destinationTime = flightInfo["arrival_time"].toString();

                qDebug() << "Departure: " << departure;
                qDebug() << "Destination: " << destination;
                qDebug() << "Departure Airport: " << departureAirport;
                qDebug() << "Destination Airport: " << destinationAirport;
                qDebug() << "Departure Time: " << departureTime;
                qDebug() << "Destination Time: " << destinationTime;

                ui->label_GoPlace->setText(departure + "——" + destination);
                ui->label_GoAirport->setText("  " + departureAirport + "——" + destinationAirport);
                ui->label_GoTime->setText("  " + departureTime + "——" + destinationTime);

                break;
            }
        }

        orderFound = found; // 设置 orderFound

        if (!orderFound) {
            QMessageBox::warning(this, "Error", "No order found with the given order ID.");
        }
    } else {
        QMessageBox::warning(this, "Error", "Failed to fetch valid order data.");
    }

    reply->deleteLater();
}

void PayWindow::on_checkBox_Wechat_stateChanged(int arg1)
{
    bool status = ui->checkBox_Wechat->isChecked();
    if (status == true) {
        ui->checkBox_Ali->setChecked(false);
        ui->checkBox_Ali->setAutoExclusive(false);
    }
}

void PayWindow::on_checkBox_Ali_stateChanged(int arg1)
{
    bool status = ui->checkBox_Ali->isChecked();
    if (status == true) {
        ui->checkBox_Wechat->setChecked(false);
        ui->checkBox_Wechat->setAutoExclusive(false);
    }
}

void PayWindow::on_pushButton_toPay_clicked()
{
    int status;

    if (ui->checkBox_Wechat->isChecked()) {
        status = 1;
    } else if (ui->checkBox_Ali->isChecked()) {
        status = 2;
    } else {
        status = 0;
    }

    switch (status) {
    case 0: {
        //创建对话框
        PayDialog *dialog = new PayDialog(this);
        //采用模态
        dialog->exec();
        //关闭对话框时自动调用delete进行释放
        dialog->setAttribute(Qt::WA_DeleteOnClose);
        break;
    }
    case 1: {
        if (orderFound) { // 只有当找到订单时，才传递 orderId
            WechatPayDialog *dialog = new WechatPayDialog(this);

            dialog->onOrderIdReceived(orderId); // 显式传递正确的 orderId
            connect(dialog,
                    &WechatPayDialog::paymentCompleted,
                    this,
                    &PayWindow::onPaymentCompleted);

            dialog->exec();
            dialog->setAttribute(Qt::WA_DeleteOnClose);
        }
        break;
    }
    case 2: {
        if (orderFound) { // 只有当找到订单时，才传递 orderId
            AliPayDialog *dialog = new AliPayDialog(this);

            dialog->onOrderIdReceived(orderId); // 显式传递正确的 orderId
            connect(dialog, &AliPayDialog::paymentCompleted, this, &PayWindow::onPaymentCompleted);

            dialog->exec();
            dialog->setAttribute(Qt::WA_DeleteOnClose);
        }
        break;
    }
    }
}

void PayWindow::onPaymentCompleted(int orderId) //完成支付后转为paid状态
{
    QNetworkRequest request(QUrl("http://127.0.0.1:8080/api/orders/pay"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject jsonData;
    jsonData["id"] = orderId;
    jsonData["order_status"] = "paid";                             // 订单状态更新为已支付
    jsonData["payment_time"] = QDateTime::currentSecsSinceEpoch(); // 当前时间戳作为支付时间

    QJsonDocument doc(jsonData);
    QByteArray data = doc.toJson();

    QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    connect(networkManager,
            &QNetworkAccessManager::finished,
            this,
            &PayWindow::onUpdateOrderStatusFinished);

    qDebug() << "Sending payment request to server...";
    networkManager->post(request, data);
}

void PayWindow::onUpdateOrderStatusFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply) {
        qWarning() << "Error: No reply received!";
        return;
    }

    QByteArray responseData = reply->readAll();

    QJsonDocument doc = QJsonDocument::fromJson(responseData);
    if (!doc.isObject()) {
        qWarning() << "Invalid response format.";
        reply->deleteLater();
        return;
    }

    QJsonObject responseObject = doc.object();
    int code = responseObject["code"].toInt();
    QString message = responseObject["message"].toString();

    if (code == 200) {
        qDebug() << "Order updated successfully: " << message;
    } else {
        qWarning() << "Order update failed: " << message;
    }

    reply->deleteLater();
}

void PayWindow::ReceivedFromUserOrder(int userId, int orderId)
{
    this->e_userId = userId;
    this->orderId = orderId;
    qDebug() << "Received userId in UserordertestWindow:" << e_userId;
    qDebug() << "Received orderId in UserordertestWindow:" << orderId;
}
